<template>
  <div class="admin-list-container">

    <!-- 标题和操作按钮 -->
    <div class="header-section">
      <h2>管理员列表</h2>
      <el-button
          type="primary"
          @click="openAddDialog"
          v-if="isSuperAdmin"
          style="background-color: #409EFF; border-color: #409EFF;"
      >
        <el-icon><Plus /></el-icon>
        新增管理员
      </el-button>
    </div>

    <!-- 搜索卡片 -->
    <el-card class="search-card" shadow="hover">
      <el-form :inline="true">
        <el-form-item label="用户名">
          <el-input placeholder="请输入用户名" v-model="searchParams.username" clearable></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input placeholder="请输入姓名" v-model="searchParams.realName" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input placeholder="请输入手机号" v-model="searchParams.phone" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchParams.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select v-model="searchParams.userType" placeholder="请选择用户类型" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="区域管理员" :value="6"></el-option>
            <el-option label="普通管理员" :value="7"></el-option>
            <el-option label="超级管理员" :value="8" v-if="isSuperAdmin"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadAdminList" style="background-color: #409EFF; border-color: #409EFF;">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 管理员表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table :data="adminList" border stripe v-loading="loading">
        <el-table-column label="序号" width="60" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column prop="realName" label="姓名" align="center"></el-table-column>
        <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
        <el-table-column label="性别" align="center" width="80">
          <template #default="scope">
            {{ formatGender(scope.row.gender) }}
          </template>
        </el-table-column>
        <el-table-column label="用户类型" align="center" width="120">
          <template #default="scope">
            {{ formatUserType(scope.row.userType) }}
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" align="center" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.registerTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220" v-if="isSuperAdmin">
          <template #default="scope">
            <el-button
                size="small"
                @click="editAdmin(scope.row)"
                style="color: #409EFF;"
                link
            >
              编辑
            </el-button>
            <el-button
                size="small"
                @click="resetPassword(scope.row.userId)"
                style="color: #409EFF;"
                link
            >
              重置密码
            </el-button>
            <el-button
                size="small"
                @click="toggleStatus(scope.row)"
                :style="{color: scope.row.status === 1 ? '#f56c6c' : '#67c23a'}"
                link
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="deleteAdmin(scope.row.userId)"
                :disabled="scope.row.userType === 8"
                link
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form ref="adminFormRef" :model="adminForm" label-width="100px" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="adminForm.username" placeholder="请输入用户名" :disabled="!!adminForm.userId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password" v-if="!adminForm.userId">
              <el-input v-model="adminForm.password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="realName">
              <el-input v-model="adminForm.realName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="adminForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="adminForm.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户类型" prop="userType">
              <el-select v-model="adminForm.userType" placeholder="请选择用户类型" style="width: 100%">
                <el-option label="区域管理员" :value="6"></el-option>
                <el-option label="普通管理员" :value="7"></el-option>
                <el-option label="超级管理员" :value="8" v-if="isSuperAdmin"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" style="background-color: #409EFF; border-color: #409EFF;">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import axios from 'axios'

// 设置axios基础URL和请求拦截器
axios.defaults.baseURL = 'http://localhost:8080'

// 添加请求拦截器
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('adminToken')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})
// 搜索参数
const searchParams = ref({
  username: '',
  realName: '',
  phone: '',
  status: '',
  userType: ''
})
// 分页参数
const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})


// 管理员列表数据
const adminList = ref([])
const loading = ref(false)

// 当前用户信息
const currentUserType = ref(0)
const isSuperAdmin = ref(false)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增管理员')
const adminFormRef = ref(null)
const adminForm = ref({
  userId: null,
  username: '',
  password: '',
  realName: '',
  phone: '',
  gender: 1,
  userType: 7,
  status: 1
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符之间', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ]
}

// 加载管理员列表
const loadAdminList = async () => {
  try {
    loading.value = true

    // 构建查询参数，过滤掉空值
    const params = {
      pageNum: pagination.value.current,
      pageSize: pagination.value.size,
      ...Object.fromEntries(
          Object.entries(searchParams.value)
              .filter(([_, value]) => value !== '' && value !== null)
      )
    }

    const res = await axios.get('/api/v1/admins/list', { params })
    if (res.data && res.data.code === 2000) {
      adminList.value = res.data.data.list || res.data.data
      pagination.value.total = res.data.data.total || res.data.total
    } else {
      ElMessage.error(res.data?.msg || '获取管理员列表失败')
    }
  } catch (error) {
    console.error('获取管理员列表失败:', error)
    ElMessage.error(error.response?.data?.msg || '获取管理员列表失败')

    // 如果未授权，跳转到登录页
    if (error.response?.status === 401) {
      localStorage.removeItem('adminToken')
      window.location.href = '/login'
    }
  } finally {
    loading.value = false
  }
}
// 重置密码
const resetPassword = async (userId) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm("确定要重置该用户的密码吗？密码将重置为默认值123456", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    // 用户点击确定后执行
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在重置密码...',
      background: 'rgba(0, 0, 0, 0.7)',
    });

    try {
      // 调用后端API重置密码
      const res = await axios.post('/api/v1/admins/reset-password', { userId });

      if (res.data.code === 2000) {
        ElMessage.success("密码已重置为123456");
      } else {
        ElMessage.error(res.data.msg || "密码重置失败");
      }
    } catch (error) {
      ElMessage.error("密码重置失败: " + (error.response?.data?.msg || error.message));
      console.error("重置密码请求错误:", error);
    } finally {
      loadingInstance.close();
    }
  } catch (error) {
    // 用户点击取消会进入这里
    if (error === 'cancel') {
      console.log('用户取消了密码重置操作');
    } else {
      console.error('密码重置确认错误:', error);
    }
  }
};
// 重置搜索
const resetSearch = () => {
  searchParams.value = {
    username: '',
    realName: '',
    phone: '',
    status: '',
    userType: ''
  }
  pagination.value.current = 1
  loadAdminList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.value.size = size
  loadAdminList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.value.current = current
  loadAdminList()
}

// 打开新增弹窗
const openAddDialog = () => {
  dialogTitle.value = '新增管理员'
  adminForm.value = {
    userId: null,
    username: '',
    password: '',
    realName: '',
    phone: '',
    gender: 1,
    userType: 7,
    status: 1
  }
  dialogVisible.value = true
}

// 编辑管理员
const editAdmin = (row) => {
  dialogTitle.value = '编辑管理员'
  adminForm.value = {
    userId: row.userId,
    username: row.username,
    password: '',
    realName: row.realName,
    phone: row.phone,
    gender: row.gender,
    userType: row.userType,
    status: row.status
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await adminFormRef.value.validate()

    let res
    if (adminForm.value.userId) {
      // 更新
      const updateParam = {
        userId: adminForm.value.userId,
        realName: adminForm.value.realName,
        phone: adminForm.value.phone,
        gender: adminForm.value.gender,
        userType: adminForm.value.userType,
        status: adminForm.value.status
      }
      res = await axios.post('/api/v1/admins/update', updateParam)
    } else {
      // 新增
      res = await axios.post('/api/v1/admins/add', adminForm.value)
    }

    if (res.data.code === 2000) {
      ElMessage.success(dialogTitle.value + '成功')
      dialogVisible.value = false
      loadAdminList()
    } else {
      ElMessage.error(res.data.msg || dialogTitle.value + '失败')
    }
  } catch (error) {
    console.error('表单提交失败:', error)
    if (error.response && error.response.data && error.response.data.msg) {
      ElMessage.error(error.response.data.msg)
    }
  }
}

// 切换状态
const toggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要${row.status === 1 ? '禁用' : '启用'}该管理员吗?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const newStatus = row.status === 1 ? 0 : 1
    const updateParam = {
      userId: row.userId,
      status: newStatus
    }

    // 使用update接口而不是单独的status接口
    const res = await axios.post('/api/v1/admins/update', updateParam)

    if (res.data.code === 2000) {
      ElMessage.success('状态更新成功')
      // 直接更新当前行的状态，避免重新加载整个列表
      row.status = newStatus
    } else {
      ElMessage.error(res.data.msg || '状态更新失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('状态更新失败:', error)
      ElMessage.error(error.response?.data?.msg || '状态更新失败')
    }
  }
}

// 删除管理员
const deleteAdmin = async (userId) => {
  try {
    await ElMessageBox.confirm('确定要删除该管理员吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await axios.post('/api/v1/admins/delete', [userId])
    if (res.data.code === 2000) {
      ElMessage.success('删除成功')
      loadAdminList()
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 格式化性别
const formatGender = (gender) => {
  return gender === 1 ? '男' : gender === 2 ? '女' : '未知'
}

// 格式化用户类型
const formatUserType = (userType) => {
  const types = {
    6: '区域管理员',
    7: '普通管理员',
    8: '超级管理员'
  }
  return types[userType] || '未知类型'
}

// 初始化
onMounted(() => {
  // 从本地存储获取当前用户信息
  const user = JSON.parse(localStorage.getItem('user'))
  if (user) {
    currentUserType.value = user.userType
    // 只有超级管理员可以管理其他管理员
    isSuperAdmin.value = user.userType === 8
  }

  loadAdminList()
})
</script>

<style scoped>
.admin-list-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
}

.breadcrumb {
  margin-bottom: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-section h2 {
  color: #304156;
  font-size: 20px;
  font-weight: 600;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 4px;
  border: none;
  background-color: #fff;
}

.table-card {
  border-radius: 4px;
  border: none;
  background-color: #fff;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  width: 100%;
}

.el-tag {
  margin-right: 5px;
}

.el-form-item :deep(.el-form-item__label) {
  color: #606266;
}

.el-radio-group {
  line-height: 32px;
}
</style>